package com.example.usermanagement.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.example.usermanagement.model.ERole;
import com.example.usermanagement.model.Role;
import com.example.usermanagement.model.User;
import com.example.usermanagement.repository.UserRepository;
import com.example.usermanagement.service.ExcelExportService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ExcelExportServiceImpl implements ExcelExportService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 用户Excel数据模型
     */
    public static class UserExcelData {
        private Long id;
        private String username;
        private String email;
        private String firstName;
        private String lastName;
        private String roles;
        private String status;

        // 构造函数
        public UserExcelData(User user) {
            this.id = user.getId();
            this.username = user.getUsername();
            this.email = user.getEmail();
            this.firstName = user.getFirstName();
            this.lastName = user.getLastName();
            // 转换角色集合为逗号分隔的字符串
            this.roles = user.getRoles().stream()
                    .map(role -> role.getName().name())
                    .collect(Collectors.joining(", "));
            // 转换启用状态为中文描述
            this.status = user.isEnabled() ? "启用" : "禁用";
        }

        // Getters (EasyExcel需要getter方法)
        public Long getId() {
            return id;
        }

        public String getUsername() {
            return username;
        }

        public String getEmail() {
            return email;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public String getRoles() {
            return roles;
        }

        public String getStatus() {
            return status;
        }
    }

    @Override
    public void exportUsersToExcel(List<User> users, HttpServletResponse response) throws IOException {
        // 设置响应头
        setResponseHeader(response, "用户列表");

        // 转换用户列表为Excel数据模型列表
        List<UserExcelData> excelData = users.stream()
                .map(UserExcelData::new)
                .collect(Collectors.toList());

        // 使用EasyExcel写入数据
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), UserExcelData.class).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("用户列表").build();
        excelWriter.write(excelData, writeSheet);
        excelWriter.finish();
    }

    @Override
    public void exportFilteredUsersToExcel(String searchQuery, String roleFilter, HttpServletResponse response) throws IOException {
        // 处理搜索关键词（去除空字符串）
        String processedSearchQuery = (searchQuery == null || searchQuery.trim().isEmpty()) ? null : searchQuery;
        
        // 处理角色筛选条件
        ERole processedRoleFilter = null;
        if (roleFilter != null && !roleFilter.trim().isEmpty() && !"all".equals(roleFilter)) {
            try {
                processedRoleFilter = ERole.valueOf(roleFilter);
            } catch (IllegalArgumentException e) {
                // 角色名称无效，使用null（即不过滤角色）
                processedRoleFilter = null;
            }
        }
        
        // 使用数据库查询方法直接获取符合条件的用户，避免在内存中过滤
        List<User> filteredUsers = userRepository.findBySearchQueryAndRole(processedSearchQuery, processedRoleFilter);

        // 导出筛选后的用户列表
        exportUsersToExcel(filteredUsers, response);
    }

    /**
     * 设置HTTP响应头，用于Excel文件下载
     */
    private void setResponseHeader(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 防止中文乱码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + encodedFileName + ".xlsx");
    }
}